package com.github.shiqiyue.app.config.security.sapi;

import com.github.shiqiyue.app.modules.sys.entity.User;
import com.github.shiqiyue.app.modules.sys.service.IUserService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

/***
 * sapi 用户信息服务
 * @author wenyao.wu
 * @since
 */
public class SapiUserDetailService implements UserDetailsService {

    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByName(username);
        SapiLoginUser loginUser = null;
        if (user != null) {
            loginUser = new SapiLoginUser();
            loginUser.setUser(user);
            //loginUser.setPermissions(userService.getPermissionsByUser(user));
            // 如果权限未空，则添加匿名的全权限
            if (CollectionUtils.isEmpty(loginUser.getPermissions())) {
                loginUser.setPermissions(Collections.singletonList("ROLE_SAPI_USER"));
            }
            loginUser.setAuthorities(loginUser.getPermissions().stream().map((item) -> {
                return new SimpleGrantedAuthority(item);
            }).collect(Collectors.toList()));
        }
        return loginUser;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
